<?php

// +----------------------------------------------------------------------
// | POS机回调
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\notify;

use app\event\pos\Pos as PosEvent;
use app\event\ucenter\User as UserEvent;
use app\model\pos\Pos as PosModel;
use app\model\pos\PosTrade as PosTradeModel;
use app\model\pos\Store as StoreModel;
use app\event\pos\PosTrade as PosTradeEvent;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserMoneyLog;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use yicmf\tools\HttpService;
use yicmf\tools\Rsa;

class Sheng extends Common
{

    /**
     * @return array|false|mixed
     * 卡种    卡种名称
     * 00    借记卡
     * 01    贷记卡
     * 03    预付卡
     * 04    未知卡种
     * 50    外卡
     * 53    JCB
     * 54    VISA
     * 55    MASTER
     * 56    AMEX
     * 57    DINERS
     * 60    境外借记卡
     * 61    境外贷记卡
     * 71    华兴钱包
     * 72    applepay借记卡
     * 73    applepay贷记卡
     * 74    数币钱包
     * 79    储值卡
     * 81    银联二维码借记卡
     * 82    银联二维码贷记卡
     * 85    建行钱包
     * 86    QQ钱包
     * 87    翼支付钱包
     * 88    微信刷脸
     * 89    支付宝刷脸
     * 91    微信钱包
     * 92    支付宝钱包
     * 93    百度钱包
     * 94    银联扫码付
     * 95    京东钱包
     * 96    拉卡拉钱包
     * 97    积分购钱包
     * 98    苏宁钱包
     * 22    银联刷脸借记
     * 21    银联刷脸贷记
     * 89    支付宝刷脸
     * 88    微信刷脸
     */


    protected $channel_id = 2;

    protected function generateSign($params)
    {
        ksort($params);
        $stringToBeSigned = $this->appSecret;
        foreach ($params as $k => $v) {
//            if(!is_string($v) && is_array($v)){
            if ($this->json_param_key == $k) {
                $stringToBeSigned .= "$k" . json_encode($v, JSON_UNESCAPED_SLASHES);
            } else {
                $stringToBeSigned .= "$k$v";
            }

        }
        unset($k, $v);
        $stringToBeSigned .= $this->appSecret;

        return strtoupper(md5($stringToBeSigned));
    }

    private function _getData()
    {
        $data = $this->request->param();
//        $data = '{"businessType":"5","dataJson":"{&quot;merchantId&quot;:&quot;43403372&quot;,&quot;promoterId&quot;:&quot;43304317&quot;,&quot;sn&quot;:&quot;00000602H3R000100031523&quot;,&quot;terminalId&quot;:&quot;502A0C6R&quot;,&quot;productNo&quot;:&quot;2024SYBmdb0&quot;,&quot;bindDate&quot;:1734077748746,&quot;merchantPhoneNoMask&quot;:&quot;177****1556&quot;,&quot;idCardNoMask&quot;:&quot;410928****6612&quot;,&quot;create_time&quot;:1734077596209}","mac":"A\/dccISs9FM3+cdBAPc\/BTfmDbPhP3+6pODdt8mWJrKLfB2DKMmaI5SGTtnGmBfxx1sbsKbV2xT8AoFXnFX7synf7\/MmKAoeeEQ\/XrxlH+bi3TYzEmVSpj84eCTurRY\/Y8yF5yIB07AdQH2s2EgjKE+yqs5Z76NPUikhZQAkwdo=","controller":"sheng","action":"pos"}';
//        $data = json_decode($data, true);
        file_put_contents($this->request->action() . '_sheng.txt', json_encode($data) . "\r\n\r\n", FILE_APPEND);

//        $data = json_decode($data, true);
        Log::write($data);
        if (isset($data['businessType'])) {
            return $this->checkRsa($data);
        } else {
            return false;
        }
    }

    public function getSign($data)
    {

        ksort($data);

        // 1                                                                                  参数
        $content = urldecode(http_build_query($data));

        // 使用私钥生成签名
        $signature = '';
        openssl_sign($content, $signature, $this->_getPrivateKey(), OPENSSL_ALGO_SHA1);//生成签名
        // openssl_sign($content,$signature,$private_key,'SHA1');//生成签名
        $encryptedData = base64_encode($signature);
        //  openssl_free_key($this->_getPrivateKey());

        return $encryptedData;
    }

    public function getSign2($content)
    {


        // 使用私钥生成签名
        $signature = '';
        openssl_sign($content, $signature, $this->_getPrivateKey(), OPENSSL_ALGO_SHA1);//生成签名
        // openssl_sign($content,$signature,$private_key,'SHA1');//生成签名
        $encryptedData = base64_encode($signature);
        //  openssl_free_key($this->_getPrivateKey());

        return $encryptedData;
    }

    /**
     * @param $file_path string
     * @return bool|string
     * @uses 获取文件内容
     */
    private function _getContents(string $file_path)
    {
        if (!file_exists($file_path)) {
            throw new Exception('密钥或公钥的文件路径错误');
        };
        return file_get_contents($file_path);
    }

    private function _getPrivateKey()
    {
        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($this->test_pri_key, 64, "\n", true)
            . "\n-----END RSA PRIVATE KEY-----";

        return openssl_pkey_get_private($private_key);
    }

    private function _getPubKey()
    {
        $public_key = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($this->test_pub_key, 64, "\n", true)
            . "\n-----END PUBLIC KEY-----";
        return $public_key;
    }


    public function testt()
    {
        return 1;

        $trade = PosTradeModel::where('id',3281)->find();


        $pos = PosModel::where('id',$trade['pos_id'])->find();


        dump($trade->toArray());
        dump($pos->toArray());

        $event = new PosTradeEvent();
        $re = $event->trade($trade, $pos);
        if ($re['code'] != 0) {
            throw new Exception($re['message']);
        }

        dump($re);
        return 1;
        exit();
//
//        $test_data = ['dddddasss'=>1];
//
//        $str = $this->getSign($test_data);
//        dump($str);
//        dump($this->verify($test_data,$str));


//        //43459370
//        $mt = explode(' ', microtime());
//
//        $param['signType'] = 'RSA';
//        $param['charType'] = 'UTF-8';
//        $param['requestId'] = uniqid();
//        $param['requestTime'] = time() . sprintf("%03d", round($mt[0] * 1000));
//        $param['promoterId'] = '43304317';
//        $param['merchantId'] = '43472512';
//
//        $param['mac'] = $this->getSign($param);
////        ksort($param);
////
////        $rsa = new Rsa($this->test_pri_key,$this->test_pub_key);
//////
//////        dump(http_build_query($param));
////        $param['mac'] = $rsa->privateEncrypt( http_build_query($param));
//        dump($param);
//        $url = 'https://syb.shengyb.cn/taskapi/PublicPushApi/queryMerchant';
//
//        $re = HttpService::post($url, json_encode($param));
//
//        dump($re);

//        $data = $re['content'];
//        $mac = $data['mac'];
//
//        unset($data['mac']);
//
//
//        $param['mac'] = $this->verify($data,$mac);
//        dump($param);
//        exit();
        $data = json_decode('{"businessType":"2","dataJson":"{&quot;merchantId&quot;:&quot;43459370&quot;,&quot;promoterId&quot;:&quot;43304317&quot;,&quot;terminalId&quot;:&quot;498A0KMM&quot;,&quot;merchantsType&quot;:2,&quot;agentId&quot;:8291,&quot;bindDate&quot;:1734576751113,&quot;merchantsName&quot;:&quot;\u738b\u6d77\u5229&quot;,&quot;mobile&quot;:&quot;155****3645&quot;,&quot;toolsNum&quot;:&quot;00000602H3R000100031400&quot;,&quot;createTime&quot;:1734576752}","mac":"NP+bT0Tcnvzht\/7kH\/Sd1R8zMPZCP28jCxlxuvebw651D3XQbWgEBPMThCsz6gPFRLOjFxxsWRaDQo0rMeASD9soAoQmiGJ5HWxLNB2zsSMoZaVS2BVQQ1gCOr2SrKXDXwX+WzcznK\/XsxKE5z3aX+Xbsk1v5eS3zmjG5QKXlcE=","controller":"sheng","action":"pos"}', true);

        $mac = $data['mac'];
        unset($data['controller']);
        unset($data['action']);
        unset($data['mac']);
        $data['dataJson'] = json_decode(htmlspecialchars_decode($data['dataJson']), true);;




        $param['mac'] = $this->verify($data,$mac);

        dump($param);
        dump($data);
        exit();
//        $data['orderNo'] = '20241220112153SYB1794';
//        $data['payStatus'] = 2;
//        $data['payMoney'] = '357000';
//        $data['payTime'] = '1734664912';
//        $data['createTime'] = '1734664912';
//        $data['pushTime'] = '1734664912';

        $data['merchantId'] = '43472512';
        $data['orderId'] = '202412201111551786426';
        $data['chargeAmount'] = '68.00';
        $data['sn'] = '00000602H3R000100031363';
//        "merchantId": "42089779",
//    "promoterId": "42064666",
//    "sn": "00000302QSNL01247391",
//    "orderId": "1486256814",
//    "chargeAmount": "60.00"
        dump($this->flow($data));
        dump($data);

        exit();
        //43472512
        //43459370
        $mt = explode(' ', microtime());

        $param['signType'] = 'RSA';
        $param['charType'] = 'UTF-8';
        $param['requestId'] = uniqid();
        $param['requestTime'] = time() . sprintf("%03d", round($mt[0] * 1000));
        $param['promoterId'] = '43304317';
        $param['merchantId'] = '43472512';

        $param['mac'] = $this->getSign($param);
//        ksort($param);
//
//        $rsa = new Rsa($this->test_pri_key,$this->test_pub_key);
////
////        dump(http_build_query($param));
//        $param['mac'] = $rsa->privateEncrypt( http_build_query($param));
        dump($param);
        $url = 'https://syb.shengyb.cn/taskapi/PublicPushApi/queryMerchant';

        $re = HttpService::post($url, json_encode($param));

        dump($re);
        $re= $this->store($re['content']['data']);
        dump($re);
    }

    public function pos()
    {
        $data = $this->_getData();
        if ($data !== false) {
            if ($data['businessType'] == 1) {
                $rep = $this->trade($data['dataJson']);
            } elseif ($data['businessType'] == 5) {
                $rep = $this->bind($data['dataJson']);
            } elseif ($data['businessType'] == 2) {
                $rep = $this->store($data['dataJson']);
            } elseif ($data['businessType'] == 4) {
                $rep = $this->flow($data['dataJson']);
            } else {
                $rep = ['ret_code' => '01', 'ret_msg' => 'FAIL'];
            }
        } else {
            $rep = ['ret_code' => '01', 'ret_msg' => 'FAIL'];
        }
        Log::write($rep);
        return  'SUCCESS';
        // Log::write(json_encode($rep));
        return json($rep);
        /**
         * {
         * "signType": "RSA",
         * "charType": "UTF-8",
         * "requestId": "d314f2b28f4f4da09cdeac0df3d9b11f",
         * "requestTime": "1613718306261",
         * "promoterId": "46921111",
         * "merchantId": "88031987",
         * "mac": "O6fcYpNlAt0Yv0o/KoWzb0kTUE8PBZW1bcrJfMigLbpu8LHmp5QDO9F/qAV08yiiB7glbhcdgBPuweI8vtYA5eC6Px5nUrPjKXHIU8fgL9sm3TQRklYvKhe85RYF+iF2UwzszB7E2dWRxERU8GopwcieO6Msra4GRCguht+gJyA="
         * }
         */

        $mt = explode(' ', microtime());

        $param['signType'] = 'RSA';
        $param['charType'] = 'UTF-8';
        $param['requestId'] = uniqid();
        $param['requestTime'] = time() . sprintf("%03d", round($mt[0] * 1000));
        $param['promoterId'] = '43304317';
        $param['merchantId'] = 'xxx';

        $param['mac'] = $this->getSign($param);
//        ksort($param);
//
//        $rsa = new Rsa($this->test_pri_key,$this->test_pub_key);
////
////        dump(http_build_query($param));
//        $param['mac'] = $rsa->privateEncrypt( http_build_query($param));
        dump($param);
        $url = 'https://syb.shengyb.cn/taskapi/PublicPushApi/queryMerchant';

        $re = HttpService::post($url, json_encode($param));

        dump($re);
        exit();

        $str = '{
  "businessType": 1,
  "dataJson": {
    "orderNo": "20240515115520SYB2631",
    "payStatus": 2,
    "payMoney": 100000,
    "payType": 3,
    "payTime": 1715745319,
    "toolsNum": "00000302QSNL01247975",
    "merchantId": "42237005",
    "channelSendSn": "1499723153",
    "createTime": 1715745319,
    "pushTime": 1715931838,
    "rate": "0.6"
  },
  "mac": "w0f4biD/FRvWNlTfi9+cN3StvyamkZ9qzamByFYXK4WBAeO941IjQcM3M9YpYB9hhVCywVhPWw24L vRiviUIs1ZtYLUbSgYMjzcv0atuPl552wNsPK0skZPKEYXkLufQT8xpbO4ZmIglPkphFpOCm2qY5WQVUZGMN6ge00HecA="
}';

        $param = json_decode($str, true);

        dump($param);

        $mac = $param['mac'];
        unset($param['mac']);
        ksort($param['dataJson']);
        dump($param);

        exit();
        $data = $this->_getData();
        $rep = ['ret_code' => '01', 'ret_msg' => 'FAIL'];
        return json($rep);
    }


    /**
     * 机具绑定回调
     * merchantId 商户号
     * promoterId 通道商户号
     * sn 机具号
     * terminalId 终端号
     * productNo 政策编号
     * bindDate  绑定日期时间戳
     * merchantPhoneNoMask 商户手机号掩码
     * idCardNoMask 商户身份证号掩码
     * create_time   商户入网时间, 时间戳
     */
    protected function bind($data)
    {

        try {

            Db::startTrans();
            //POS机处理
            $pos = PosModel::where('sn', $data['sn'])->where('channel_id', $this->channel_id)->find();
            if (!$pos) {
                throw new Exception('无pos');
            }
            $store = StoreModel::where('store_sn', $data['merchantId'])->find();
            if (!$store) {
                $store['channel_id'] = $this->channel_id;
                $store['mobile'] = isset($data['merchantPhoneNoMask']) ? $data['merchantPhoneNoMask'] : '';
                $store['store_sn'] = $data['merchantId'];
                $store['pos_sn'] = $data['sn'];
                $store['user_id'] = $pos['user_id'];
                $store = StoreModel::create($store);
            }
            $pos['store_id'] = $store['id'];
            $pos['term_no'] = $data['terminalId'];
            $pos['merch_no'] = $data['merchantId'];
            $pos['bind_time'] = time_format(round($data['bindDate'] / 1000));
            $pos['model'] = $data['productNo'];
            if (!$pos->save()) {
                throw new Exception('资料保存异常');
            }
            Db::commit();
            $rep = ['ret_code' => '00', 'ret_msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['ret_code' => '01', 'ret_msg' => $e->getMessage()];
        }
        return $rep;
    }


    /**
     * 商户信息推送
     * merchantId  商户id
     * promoterId 上级代理id
     * terminalId 终端号
     * merchantsType 商户类型 1企业 2小微 3个体户：
     * agentId 代理id
     * bindDate 绑定时间
     * merchantsName 商户名
     * mobile 联系手机
     * toolsNum 机具号
     * createTime 商户入网时间
     */
    protected function store($data)
    {

        try {
            Db::startTrans();
            if (!empty($data['toolsNum']))
            {
                //POS机处理
                $pos = PosModel::where('sn', $data['toolsNum'])->where('channel_id', $this->channel_id)->find();
                if (!$pos) {
                    throw new Exception('无pos');
                }
                $store = StoreModel::where('store_sn', $data['merchantId'])->find();
                if (!$store) {
                    $store['channel_id'] = $this->channel_id;
                    $store['mobile'] = isset($data['mobile']) ? $data['mobile'] : '';
                    $store['store_sn'] = $data['merchantId'];
                    $store['nickname'] = $data['merchantsName'];//merchantsName
                    $store['type'] = $data['merchantsType'];//1企业 2小微 3个体户：
                    $store['pos_sn'] = $data['toolsNum'];
                    $store['user_id'] = $pos['user_id'];
                    $store = StoreModel::create($store);
                } else {
                    $store['nickname'] = $data['merchantsName'];
                    $store['mobile'] = $data['mobile'];
                    $store['type'] = $data['merchantsType'];//1企业 2小微 3个体户：
                    $store['pos_sn'] = $data['toolsNum'];
                    $store['user_id'] = $pos['user_id'];
                    $store->save();
                }
                $pos['store_id'] = $store['id'];
                $pos['term_no'] = $data['terminalId'];
                $pos['merch_no'] = $data['merchantId'];
                if (!$pos->save()) {
                    throw new Exception('资料保存异常');
                }
            }else{
                // 解绑
            }

            Db::commit();
            $rep = ['ret_code' => '00', 'ret_msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['ret_code' => '01', 'ret_msg' => $e->getMessage()];
        }
        return $rep;
    }


    /**
     * 流量费
     * merchantId 商户号
     * promoterId 通道商户号
     * sn 机具号
     * orderId 订单号
     * chargeAmount  扣款金额（全部扣款成功后通知），单位元
     */
    public function flow($data)
    {
        try {
//            Db::startTrans();
            //POS机处理
            $pos = PosModel::where('sn', $data['sn'])->where('channel_id', $this->channel_id)->find();
            if (!$pos) {
                // 新增无主pos机
                throw new Exception('无pos');
            }

            $event = new PosEvent();
            $re = $event->flow($pos,$data['orderId'],2);
            if ($re['code'] != 0) {
                throw new Exception($re['message']);
            }

//            if ($pos['cashback_user_id'] || $pos['buy_user_id']) {
//                //参加返现
//                if ($pos['cashback_user_id']) {
//                    $user = UserModel::where('id', $pos['cashback_user_id'])->find();
//                } else {
//                    $user = UserModel::where('id', $pos['buy_user_id'])->find();
//                }
//                if ($user) {
//                    // 流量费返现
//                    $log = UserMoneyLog::where('order_id', $data['orderId'])->where('type', 91)->where('channel', 1)->where('user_id', $user['id'])->find();
//                    if (!$log) {
//                        //参加返现
//                        $amount = 40;
////                            $user['my_balance'] = $user['my_balance'] + $data['amount'] / 100;
//                        $user['my_balance'] = $user['my_balance'] + $amount;
//                        $user->save();
//                        UserEvent::money($amount, $user['id'], '流量返现（' . $pos['sn'] . '）', 91, $pos['user_id'], $data['orderId'], 0, 1, 16);
//                    }
//                }
//
//            }
//            Db::commit();
            $rep = ['ret_code' => '00', 'ret_msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['ret_code' => '01', 'ret_msg' => $e->getMessage()];
        }
        return $rep;
    }

    public function test()
    {
        $s = 'IC0zYAaJUfB05JcWewM+zOESvrg1JhASyUCDEHX4pgf1xVt3sGezrzK22GkNGyStcPkH2hjntt8DJm0ry9iIAgig0LlFQWD4IfTq56EY7jEWvsv5kZ78Tf+Sfc6rQrLEnX7vEDbQFMbaFepFBoXRjv1o3bB1IPAlywUuFzh8yRNs628ylDylGYWDm7ED85zL4sbfZVuwuMLnw4YqV4P0pPK/2nLpEzKeMF3Kol9zAq2pT9VVJU1gfoD7f9neAme+pBKciUA8AvyvMT0cFSs3RM5b7LnO6fz9TxU3N4y6H9okvdze5SztorG69hfdF0+YBhl43Ga3gYSIXLwid1zrfx48Aj+G9ABHMOvu0kU4L5W016SLbcRjiXmgZPsWOMDuUI52DtxN/A6doZgnLHl7oZ/dd/lGLjamQnEQZ5UG1jfM+Rm1Zher8A87brA/7iPzyM7l3Lff3l8p4UzUEtP2F533muOLMwe7OtsxFFVKSiZPPVhOP4FHPM0SKwQ90FLye/LhXdlKIHi4m1Nos7y+z8bd9KZKEaVGE964AD7Jtfs5zhzZzajJXPcBhg7wb/sIHHXtwebfw0j90ItVULg/s3jU1nHfj9A9Qonnzuht3rX/YGsuivo3dHsRW18Iuqi6MQ6rPss5HL96YxfiZJQkTs6qZoXFUpvHgWL9I8BRzGQ=';
        $s = 'KbtdTs60yIE8U2c\/BjkrzOQCiDi\/kZYqQgYfKdN4NPBrJmQXU96qBMGL9bsJKnFq3Vnr6BF9t6vFBvz1SV+V49Hmg0BbfSfdYaesrLBeaDTJ0R18RVpNJCLzoYF4vcDx6iQYpaX11hke11L\/xds5UbO8neLnJyWdO4XF+yndE8li7KHDkveTh7K102vcrVLDPp\/Hhn6\/rg3PFftf9XdYWLbJMqey\/zblTXxqdhQZX\/h67CX8IxM+Nqad1EycwqmdHcQdjmnzCeClT00mWhoKJLeNaP18YWG+xvOXmfR4A49al1Sduy77m498WTfzJVCnCxNVeXU7XfJEYd8tPq9Mgg==';

        $rsa = new Rsa($this->test_pri_key, $this->test_pub_key);
        $re = $rsa->publicDecrypt($s);
        dump(json_decode($re, true));

    }

    /**
     * orderNo 订单编号
     * payStatus  支付状态：2: 已支付
     * payMoney 支付金额 单位：分
     * payType 支付类型 微信|1,支付宝|2,贷记卡|3,借记卡|4,银联二维码|5,云闪付|6,银联优惠|7,其他|0
     * payTime 支付时间
     * toolsNum 机具号
     * merchantId 商户号
     * channelSendSn 渠道交易号
     * createTime 订单创建时间
     * pushTime 推送时间
     * rate  费率 (借记卡有封顶值，用逗号隔开)
     * "orderNo": "20240515115520SYB2631",
     * "payStatus": 2,
     * "payMoney": 100000,
     * "payType": 3,
     * "payTime": 1715745319,
     * "toolsNum": "00000302QSNL01247975",
     * "merchantId": "42237005",
     * "channelSendSn": "1499723153",
     * "createTime": 1715745319,
     * "pushTime": 1715931838,
     * "rate": "0.6"
     */
    protected function trade($data)
    {
        try {
            $trade = PosTradeModel::where('channel_id', $this->channel_id)->where('order_sn', $data['orderNo'])->find();
            if ($trade) {
                throw new Exception('已经处理');
            }
            $insert = [];
            $insert['order_sn'] = $data['orderNo'];
            $insert['pos_sn'] = $data['toolsNum'];
            $insert['refer_no'] = $data['channelSendSn'];
            $insert['merch_no'] = $data['merchantId'];//merchantId
            $insert['term_no'] = $data['toolsNum'];//merchantIdterm_no
            $insert['trans_time'] = time_format($data['createTime']);
            $insert['trans_sn'] = $data['orderNo'];//
            $insert['status'] = $data['payStatus'] == 2 ? 1 : $data['payStatus'];
            $insert['pay_type'] = $data['payType'];
//                $insert['trans_sn'] = $data['ologNo'];
            $insert['amount'] = round((float)$data['payMoney'] / 100, 2);

            if (in_array($insert['pay_type'], [4])) {
                $insert['card_type'] = 1;// 微信|1,支付宝|2,贷记卡|3,借记卡|4,银联二维码|5,云闪付|6,银联优惠|7,其他|0
            } else {
                $insert['card_type'] = 2;
            }
            if (in_array($insert['pay_type'], ['3'])) {
                $insert['trade_type'] = 1;
            } elseif (in_array($insert['pay_type'], ['1', '2', '5'])) {
                $insert['trade_type'] = 2;
            } else {
                $insert['trade_type'] = 3;
            }

            $insert['type'] = 1;
            $insert['channel_id'] = $this->channel_id;
            $insert['channel'] = 'sft';
            // pos机查询
            $pos = PosModel::where('sn', $insert['pos_sn'])->where('status', 1)->find();
            if ($pos) {
                $insert['pos_id'] = $pos['id'];
                $insert['user_id'] = $pos['user_id'];
                if ($pos['store_id']) {
                    $insert['store_id'] = $pos['store_id'];
                }
//                } else {
//                    // 新增商户信息
//                    $store['nickname'] = $data['customerName'];
//                    $store['store_sn'] = $data['externalCustomerNo'];
//                    $store['contacts'] = $data['legalName'];
//                    $store['pos_sn'] = $data['posSn'];
//                    $store['channel_id'] = 1;
//                    $store['channel'] = 'la';
//                    $store = StoreModel::create($store);
//                    $pos['store_id'] = $store['id'];
//                    $pos->save();
//                    $insert['store_id'] = $pos['store_id'];
//                }
                $insert['agent_id'] = $pos['agent_id'];
            } else {
                throw new Exception('未知');
            }
            $trade = PosTradeModel::create($insert);
            if (!$trade) {
                throw new Exception('数据异常');
            }
            if ($trade['status'] == 1 && ($insert['trade_type'] == 1 || $insert['trade_type'] == 2)) {
                $event = new PosTradeEvent();
                $re = $event->trade($trade, $pos);
                if ($re['code'] != 0) {
                    throw new Exception($re['message']);
                }
            }
            $rep = ['ret_code' => '00', 'ret_msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['ret_code' => '01', 'ret_msg' => $e->getMessage()];
        }
        return $rep;
    }

    /**
     * 私钥加密
     * @param $data
     * @return string
     */
    public static function privateKeyDecrypt($data, $privateKey)
    {
        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($privateKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_private_encrypt($chunk, $encryptData, $privateKey);
            $crypto .= $encryptData;
        }
        $encrypted = base64_encode($crypto);
        return $encrypted;
    }

    /**
     * 公钥解密
     * @param $data
     * @return string
     */
    public static function publicKeyDecrypt($data, $pubKey)
    {
        $pubKey = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($pubKey, 64, "\n", true)
            . "\n-----END PUBLIC KEY-----";
        $crypto = '';
        foreach (str_split(base64_decode($data), 128) as $chunk) {
            openssl_public_decrypt($chunk, $decryptData, $pubKey);
            $crypto .= $decryptData;
        }
        return $crypto;
    }

    /**
     * 校验
     * @return void
     */
    protected function checkRsa($data)
    {

        $mac = $data['mac'];
        $data['dataJson'] = json_decode(htmlspecialchars_decode($data['dataJson']), true);;
        return $data;
        dump($data);


//        $sign = $this->getSign($data['dataJson']);

        dump($this->verify($this->test_pub_key,$data['dataJson'],$mac));
//        dump($sign);
        dump($mac);
        dump($data);


        exit();
        return $data;

        $rsa = new Rsa($this->test_pri_key, $this->test_pub_key);

        dump($data['mac']);

        dump($data['dataJson']);

        dump($data);
        exit();
        $re = $rsa->publicDecrypt($data['data']);
        file_put_contents($this->request->action() . '_la.txt', $re . "\r\n\r\n", FILE_APPEND);
        $json = json_decode($re, true);
        if (is_array($json)) {
            return $json;
        } else {
            return false;
        }
    }


    /**
     * 加签
     *
     * @param string $privateKey RSA私钥
     * @param string $data 加签数据
     * @return string 签名的Base64编码
     */
    protected function sign($privateKey, $data)
    {
        $privateKeyId = openssl_pkey_get_private($privateKey);
        openssl_sign($data, $signature, $privateKeyId, OPENSSL_ALGO_SHA256);
        return base64_encode($signature);
    }

    /**
     * 验证数字签名
     *
     * @param string $publicKey RSA公钥
     * @param string $data 原文
     * @param string $signature 签名的Base64编码
     * @return bool 验证是否成功
     */
    protected function verify($data, $signature)
    {

//          ksort($data['dataJson']);
        ksort($data);
        if (isset($data['dataJson']))
        {

            ksort($data['dataJson']);

//          $data_str = '';
            foreach ($data['dataJson'] as $k => $v) {

                $data['dataJson'][$k] = (string)$v;
            }

            $data['dataJson'] = json_encode($data['dataJson'], JSON_UNESCAPED_UNICODE);
        }



//        dump(urldecode(json_encode($data['data'], JSON_UNESCAPED_UNICODE)));exit();
//        $str = '';
//        foreach ($data as $k => $v) {
//            if ($str)
//            {
//                $str.='&'.$k.'='.$v;
//            }else{
//                $str.=$k.'='.$v;
//            }
//        }
//        $str.='&success=true';

//        $str = str_replace('respCode=00','respCode="00"',$str);
//        $data['dataJson'] = json_encode($data['dataJson']);

        // 1
        //

        $str = urldecode(http_build_query($data));
        $publicKeyId = openssl_pkey_get_public($this->_getPubKey());
        return openssl_verify($str, base64_decode($signature), $publicKeyId);
        dump(openssl_verify($str, base64_decode($signature), $publicKeyId));
//        dump(openssl_verify($str, $signature, $publicKeyId));
        return ;
        return openssl_verify($str, base64_decode($signature), $publicKeyId);
        return $result === 1;
    }

    /**
     * 使用sha256算法进行数据摘要
     *
     * @param string $data 摘要原文
     * @return string 摘要的Hex编码
     */
    protected function sha256($data)
    {
        return hash('sha256', $data, false);
    }

    protected $test_pri_key = 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJBWbyj6NsWZ+UpJxTWom287YtvzUigXI/P9SnQqTf/aXFC+NsIVimBL4evCvSMW7oytgt7B7G41cQLTrTzBwnj2hGDpct7BtVt8tRIZUG2BLhcvMzr4tVCiaVn1Iqo1EFSGCt3aS0p2OGbkqCvOMqDjnyBTG5X3XTkh/lw3Xb6RAgMBAAECgYA8E53lAnB1wubeIuJwuSMpIyC8yAQ0J52RWqX4v/sDOVIfUWzdT7Xu6ua4CLBMwKi96SKFsVXFcXz+XjjHByb4LCG9C23D2qjYBob8EncdkFk2hbmrBpn/Hg4rqwmhWZlzp5lH/R+w/90bkI2rbITqgBMTSqFqvQZGUMxDyW8wIQJBAOGNPLuJRfDihpHjELJX1v81AsDj/VvnFr/5e7npQo+tsFD5AQVNO/6I16vUv2vHmJSE4/lh7I1AdyagFzDND30CQQCj0oxSTKHz3Cwu+3/qSqFJWzMcTYtapsspWwlL5fhK6Ga+1KPErz3KRX9KKFGnlM3jbLc9Dqgr6zZACohRXz+lAkB90Hf5MFiIRwPDqwJsSR1PnHVdvY9dTWleSr8edCRB2yQH9u3/1BZMJG8RlYn1iA/vgLVeLaZzIGuWaySkfy5NAkEAh3sdrwZPPXSNWcGGdQWJQzhYGYULxUmBZM8z7f/fClwOdK04TvW6PSiib3rOpK/MYdPL6oPPkpqwP+A2Ak2qPQJAU9u1BcABrWrn6TL+VU87tE4qUwXIRQqYn+EAs95C2KZMzDdvZ81iWMSodrwlX15AhveN1HKaOOWGS3fqiwnVRw==';
    protected $test_pub_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCQVm8o+jbFmflKScU1qJtvO2Lb81IoFyPz/Up0Kk3/2lxQvjbCFYpgS+Hrwr0jFu6MrYLewexuNXEC0608wcJ49oRg6XLewbVbfLUSGVBtgS4XLzM6+LVQomlZ9SKqNRBUhgrd2ktKdjhm5KgrzjKg458gUxuV9105If5cN12+kQIDAQAB';
}
